const fs = require("node:fs");
const record = require("node-record-lpcm16");
const vosk = require("vosk");
const path=require("path")
// 模型路径
const MODEL_PATH = path.resolve(__dirname, "../public/vosk-model-small-cn-0.22"); // 替换为你的模型路径
const SAMPLE_RATE = 16000;

// 初始化 Vosk 模型
if (!fs.existsSync(MODEL_PATH)) {
    console.error("Model path does not exist.");
    process.exit(1);
}
vosk.setLogLevel(0);
const model = new vosk.Model(MODEL_PATH);

// 处理音频数据
const recognizer = new vosk.Recognizer({
    model: model,
    sampleRate: SAMPLE_RATE,
});

// 开始录音
const mic = record.record({
    sampleRateHertz: SAMPLE_RATE,
    threshold: 0, // 录音的阈值
    verbose: false, // 是否打印详细信息
    recordProgram: "arecord", // 或 "arecord" 根据你的操作系统选择
});

mic.stream().on("data", (data) => {
    if (recognizer.acceptWaveform(data)) {
        const result = recognizer.result();
        // console.log("结果", JSON.stringify(result, null, 4));
        console.log("结果", result.text);
    } else {
        const partialResult = recognizer.partialResult();
        // console.log("partial", JSON.stringify(partialResult, null, 4));
        console.log("partial", partialResult.partial);
    }
});

mic.stream().on("error", (err) => {
    console.error("Error in Input Stream: " + err);
});

mic.stream().on("startComplete", () => {
    console.log("Microphone started.");
});

mic.stream().on("stopComplete", () => {
    console.log("Microphone stopped.");
});

mic.start();

// 在进程退出时进行清理
process.on("SIGINT", () => {
    console.log("Exiting...");
    recognizer.free();
    model.free();
    mic.stop();
    process.exit();
});



// const { exec } = require('child_process');
// const iconv = require('iconv-lite');
// exec(`powershell.exe Add-Type -AssemblyName System.speech; $speak = New-Object System.Speech.Synthesis.SpeechSynthesizer; $speak.Rate = 5; $speak.Speak([Console]::In.ReadLine()); exit`).stdin.end(iconv.encode('别不信', 'gbk'));